<?php
/**
 * Created by PhpStorm.
 * User: xiandanjia
 * Date: 2018/10/23
 * Time: 下午 4:57
 */

namespace App\Components;


use Swoft\App;
/**
 * 工具类
 * @author Jss
 * 2018年10月23日 17:04:02
 * Class Tool
 * @package App\Components
 */
class Tool
{
    /**
     * log记录方法
     * @param $log 字符串或者数组
     * @param $logpath 缓存文件名称
     */
    public static function log($log,$logpath = ''){
        if (!$logpath){
            $logpath = date('Y-m-d').'.log';
        }
        $text = '['.date('Y-m-d H:i:s').']:';
        if (is_array($log)){
            $text .= "\r\n";
            $text .= var_export($log,true);
        }else{
            $text .= $log;
        }
        $text .= "\r\n";
        $logpath = app::getAlias('@runtime').'/logs/'.$logpath;
        return swoole_async_write($logpath,$text);

    }
    /**
     * 实现 key=val1&key=val2
     * @param array $formData 数据数组
     * @param string $numericPrefix 数字索引时附加的Key前缀
     * @param string $argSeparator 参数分隔符(默认为&)
     * @param string $prefixKey Key 数组参数，实现同名方式调用接口
     * @return string
     */
    public static function build_query($formData, $numericPrefix = '', $argSeparator = '&', $prefixKey = '') {
        $str = '';
        foreach ($formData as $key => $val) {
            if (!is_array($val)) {
                $str .= $argSeparator;
                if ($prefixKey === '') {
                    if (is_int($key)) {
                        $str .= $numericPrefix;
                    }
                    $str .= urlencode($key) . '=' . urlencode($val);
                } else {
                    $str .= urlencode($prefixKey) . '=' . urlencode($val);
                }
            } else {
                if ($prefixKey == '') {
                    $prefixKey .= $key;
                }
                if (isset($val[0]) && is_array($val[0])) {
                    $arr = array();
                    $arr[$key] = $val[0];
                    $str .= $argSeparator . http_build_query($arr);
                } else {
                    $str .= $argSeparator . self::build_query($val, $numericPrefix, $argSeparator, $prefixKey);
                }
                $prefixKey = '';
            }
        }
        return substr($str, strlen($argSeparator));
    }

    public static function curl($action, $params, $httpMethod='POST', $contentType='urlencoded') {

        $ch = curl_init();
        $httpHeader = ['timestamp:'.time()];
        if ($httpMethod=='POST' && $contentType=='urlencoded') {
            $httpHeader[] = 'Content-Type:application/x-www-form-urlencoded';
            curl_setopt($ch, CURLOPT_POSTFIELDS, self::build_query($params));
        }
        if ($httpMethod=='POST' && $contentType=='json') {
            $httpHeader[] = 'Content-Type:Application/json';
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params) );
        }
        if ($httpMethod=='GET' && $contentType=='urlencoded') {
            $action .= strpos($action, '?') === false?'?':'&';
            $action .= self::build_query($params);
        }
        curl_setopt($ch, CURLOPT_URL, $action);
        curl_setopt($ch, CURLOPT_POST, $httpMethod=='POST');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false); //处理http证书问题
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $ret = curl_exec($ch);
        if (false === $ret) {
            $ret =  curl_errno($ch);
        }
        curl_close($ch);
        return $ret;
    }

    /**
     * @param $key
     * @return string
     * @description 生成memcached key
     */
    public static function buildMemcachedKey($key)
    {
        if (is_string($key)) {
            $key = ctype_alnum($key) && static::byteLength($key) <= 32 ? $key : md5($key);
        } else {
            $key = md5(json_encode($key));
        }

        return self::$keyPrefix . $key;
    }

    /**
     * Returns the number of bytes in the given string.
     * This method ensures the string is treated as a byte array by using `mb_strlen()`.
     * @param string $string the string being measured for length
     * @return integer the number of bytes in the given string.
     */
    public static function byteLength($string)
    {
        return mb_strlen($string, '8bit');
    }
}